#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import datetime
import django.utils.simplejson
import re
import string
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from appengine.billmodel import Bill

class GetTrend(webapp.RequestHandler):
	def post(self):
		search_date = datetime.date.today() - datetime.timedelta(6 * 30)
		if self.request.get("category") == "0":
			bills = db.GqlQuery("SELECT * FROM Bill WHERE AccountName=:1 AND CreateTime>=:2 ORDER BY CreateTime ASC", self.request.get("user"), datetime.date(search_date.year, search_date.month, 1))
		else:
			bills = db.GqlQuery("SELECT * FROM Bill WHERE AccountName=:1 AND CreateTime>=:2 AND BillCategory=:3 ORDER BY CreateTime ASC", self.request.get("user"), datetime.date(search_date.year, search_date.month, 1), self.request.get("category"))
		bill_month = {}
		for bill in bills:
			bill_month_key = u"%(year)04d-%(month)02d" % {"year":bill.CreateTime.year, "month":bill.CreateTime.month}
			if bill_month.has_key(bill_month_key):
				bill_month[bill_month_key] += bill.PayAmount
			else:
				bill_month[bill_month_key] = bill.PayAmount

		chart1_data = []
		bill_month_keys = bill_month.keys()
		bill_month_keys.sort()
		for key in bill_month_keys:
			chart1_data.append([key, ("%0.02f" % bill_month[key])])
		self.response.out.write("({ErrCode:0, ErrMsg:'', xml:"+django.utils.simplejson.dumps(chart1_data)+"})")

application = webapp.WSGIApplication([('/interface/gettrend.php', GetTrend)], debug=True)

def main():
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
	main()

